<?php
/*
 *  file system(文件系统)
 *  2016年10月26日 星期三
*/
namespace Hyang\Util;
class fs{
    private $fname;
    private $option = array();
    public function __construct($filename=null)
    {
        $this->fname = $filename;
    }
    // 文件存储- $type =>[JSON/BASE/SERI/TEXT]
    public function cache($data=null,$fname=null)
    {
        
        $opt = $this->option;
        if(empty($fname)) $fname = $this->getVal('file');
        if(empty($fname)) $fname = $this->fname;
        $type = isset($opt['type'])? $opt['type']:'TEXT';
        $content = "";
        if(isset($opt['data']) && empty($opt['data'])) $data = $opt['data'];
        if(empty($data)){
            if(is_file($fname)) $content = file_get_contents($fname);
            else return "";
        }
        switch($type){
            case 'JSON':
                if($content) return json_decode($content,true);
                $content = is_array($data)? json_encode($data):$data;
                break;
            case 'SERI':
                if($content) return unserialize($content);
                if($data) $content = serialize($data);
                break;
            case 'BASE':
                if($content) return base64_encode($content);
                if($data) $content = base64_encode($data);
                break;
            default:
                if($content) return $content;
                if($data) $content = $data;
        }
        if($content) file_put_contents($fname,$content);
    }
    public function append($data=null,$fname=null)
    {
        if(empty($fname)) $fname = $this->getVal('file');
        if(empty($fname)) $fname = $this->fname;
        if(empty($data)) $data = $this->getVal('data');
        if(empty($data) || empty($fname)) return '';
        if(is_array($data) || is_object($data)){
            $data = is_array($data)? $data:(array)$data;
            $data = print_r($data,true);
        }
        $fh = fopen($fname,'a');
        fwrite($fh,$data);
        fclose($fh);

    }
    // 获取数据选项值
    public function getVal($key=null)
    {
        if(empty($key)) return $this->option;
        if(isset($this->option[$key])) return $this->option[$key];
        return '';
    }
    /*链式操作处理*/
    // 选项值： file/data/type(cache)
    public function setOption($key,$value=null)
    {
        if(is_array($key)){
            foreach($key as $k=>$v){
                $this->option[$k] = $v;
            }
        }
        elseif($value) $this->option[$key] = $value;
        return $this;
    }    
}